<template>
  <div id="content">
    <div style="width: 100%; text-align: right; padding: 10px">
      <a-dropdown @select="handleSelect">
        <a-button type="primary">批量</a-button>
        <template #content>
          <a-doption @click="BatchDownload">条码下载</a-doption>
          <a-doption>条码打印</a-doption>
        </template>
      </a-dropdown>
    </div>
    <a-table
      :pagination="true && pagination"
      :data="qrCodeData"
      @page-change="pageChange($event, 'page')"
      @page-size-change="pageChange($event, 'size')"
      :row-selection="rowSelection"
      v-model:selectedKeys="selectedKeys"
      @select="onSelect"
      :args="args"
      row-key="id"
    >
      <template #columns>
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column :width="100" title="条码" align="center"
          ><template #cell="{ record }">
            <QRcode
              ref="qrcode"
              :qr-url="`${record.content}`"
              :qr-text="`${record.content}`"
          /></template>
        </a-table-column>
        <a-table-column :width="100" title="条码格式" align="center"
          ><template #cell="{ record }">
            {{ record.format === 1 ? 'QR二维码' : '条形码' }}
          </template>
        </a-table-column>
        <a-table-column
          :width="100"
          title="条码类型"
          data-index="name"
          align="center"
          ><template #cell="{ record }">
            {{ record.type === 1 ? '物料条码' : '物料包装条码' }}
          </template>
        </a-table-column>
        <a-table-column
          :width="100"
          title="条码内容"
          data-index="location"
          align="center"
          ><template #cell="{ record }">
            <a-textarea
              v-model="record.content"
              placeholder="Please enter something"
              disabled
              allow-clear
            />
          </template>
        </a-table-column>
        <a-table-column
          :width="100"
          title="启用状态"
          data-index="tier"
          align="center"
          ><template #cell="{ record }">
            <a-typography-text type="success">
              {{ record.state === 1 ? '已启用' : '' }}
            </a-typography-text>
          </template>
        </a-table-column>
        <a-table-column
          :width="100"
          title="操作"
          data-index="tier"
          align="center"
          ><template #cell="{ record, rowIndex }">
            <a-space>
              <a-dropdown @select="handleSelect">
                <a-button type="primary">更多功能</a-button>
                <template #content>
                  <a-space direction="vertical" fill>
                    <a-button type="text">条码打印</a-button>
                    <a-button type="text" @click="bb(rowIndex)"
                      >条码下载</a-button
                    >
                    <a-popconfirm
                      content="确认删除?"
                      type="error"
                      @ok="delQrcode(record.id)"
                    >
                      <a-button type="text" status="danger">条码删除</a-button>
                    </a-popconfirm>
                  </a-space>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { getBarcode, delarcode } from '@/api/barcode';
  import dayjs from 'dayjs';
  import { cloneDeep } from 'lodash';
  import Message from '@arco-design/web-vue/es/message';

  const qrcodeRef = ref();
  const router = useRouter();
  const route = useRoute();
  const props = withDefaults(
    defineProps<{
      orderInfo: any;
    }>(),
    {}
  );

  const selectedKeys = ref([]);
  // const selectedlist = ref([])
  const selectedIndex = ref([]);

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const pagination = reactive({
    // 分页数据
    showTotal: true,
    showJumper: true,
    showPageSize: true,
    current: 1,
    total: 0,
    pageNumber: null,
  });

  const params = reactive({
    // 分页数据，用于请求
    page: 1,
    size: 10,
  });

  const args = {
    bordered: {
      headerCell: true,
    },
    stripe: true,
  };

  const orderInfo = ref(props.orderInfo);
  const modelVisible = ref(false);
  const id = Number(route.query.id);
  // 获取对应列表信息
  const qrCodeData = ref();
  const getData = async (page?: any) => {
    try {
      const res = await getBarcode({ ...params, orderId: id, module: 2 });
      const { content, pageable } = res;
      qrCodeData.value = content;
      pagination.current = pageable.pageNumber;
      pagination.total = pageable.totalItems;
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getData();
  const pageChange = (val: number, key: 'page' | 'size') => {
    params[key] = val;
    getData();
  };

  const onSelect = (e: any, id: number, d: any) => {
    const msg: any = qrCodeData.value.findIndex((i: any) => i.id === id);
    if (selectedIndex.value.indexOf(msg) === -1) {
      selectedIndex.value.push(msg);
    } else {
      const res = selectedIndex.value.splice(
        selectedIndex.value.indexOf(msg),
        1
      );
    }
  };

  const bb = (index: number) => {
    let canvas1 = document.getElementById('content');
    if (!canvas1) return;
    let canvas = canvas1.getElementsByTagName('canvas');
    let a = document.createElement('a');
    a.href = canvas[index].toDataURL('img/png');
    a.download = '二维码';
    a.click();
    Message.error('下载中，请稍后...');
  };

  const BatchDownload = () => {
    let canvas1 = document.getElementById('content');
    if (!canvas1) return;
    let canvas = canvas1.getElementsByTagName('canvas');
    selectedIndex.value.forEach((item) => {
      let a = document.createElement('a');
      a.href = canvas[item].toDataURL('img/png');
      a.download = '二维码';
      a.click();
    });
  };

  const generateBarCode = () => {
    modelVisible.value = true;
  };

  const delQrcode = async (id?: number) => {
    await delarcode({ id });
    getData();
  };
</script>

<style scoped lang="less">
  #content {
    padding: 20px;
  }

  .arco-space-item :nth-child(1) {
    text-align: right;
  }
</style>
